import React, {Component} from "react";
import {
  StyleSheet, Text, View, FlatList, RefreshControl,
  Image, TouchableOpacity, ActivityIndicator,DeviceInfo
} from "react-native";
import {connect} from 'react-redux';
import Toast from 'react-native-easy-toast';
import {createOnLoadMoreTrending, createOnLoadTrendingData} from '../../redux/actions/index'
import Ionicons from 'react-native-vector-icons/Ionicons'

const URL = 'https://github.com/trending?q=';  // 查询路径
const QUERY_STR = '&since=daily';  // 按照点赞数排序
const PAGE_SIZE = 10;   // 页面数据数量

// 趋势页面内容
class TrendingTop extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pageData: [],
      refreshing: true, // 是否刷新,true刷新，false不刷新
    }
  }

  render() {
    let {refreshing} = this.state;
    let store = this.store();

    return <View style={styles.container}>
      <FlatList
        data={store.projectModes}
        renderItem={this.renderItem}
        keyExtractor={item => item.id + ''}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={this.onRefresh}/>
        }
        ListFooterComponent={this.footerCom}
        onEndReached={() => {
          // 让onEndReached晚100毫秒执行，
          setTimeout(() => {
            if (this.canLoadMore) {
              this.loadData(true);
              this.canLoadMore = false
            }
          }, 100)
        }
        }
        onMomentumScrollBegin={() => {  // 用户开始滚动
          this.canLoadMore = true
        }
        }
        onEndReachedThreshold={0.5}
      />
      <Toast ref="toast" position={'center'}/>
    </View>
  }

  componentDidMount() {
    // 加载数据
    this.loadData()
  }

  shouldComponentUpdate(nextProps, nextState) {
    let {trending, route} = nextProps;

    // 当传过来数据isLoading是false时，设置页面数据
    if (trending[route.name] && !trending[route.name].isLoading) {
      nextState.pageData = trending[route.name] && trending[route.name].items;
      nextState.refreshing = trending[route.name] && trending[route.name].isLoading
    }
    return true
  }

  componentWillUnmount() {
    clearTimeout(this.timeId)
  }

  // 加载数据
  loadData = (loadMore) => {
    let {onLoadTrendingData, route, onLoadMoreTrending} = this.props;
    const store = this.store();
    const url = this.getFetchUrl(route.name);
    if (loadMore) {
      onLoadMoreTrending(route.name, ++store.pageIndex, PAGE_SIZE, store.items, () => {
        this.refs.toast.show('没有更多了')
      })
    } else {
      // 从本地或者网络获取数据
      onLoadTrendingData(route.name, URL, PAGE_SIZE);
    }
  };

  store = () => {
    const {trending, route} = this.props;
    let store = trending[route.name];
    if (!store) {
      store = {
        items: [],
        isLoading: false,
        projectModes: [], // 要显示的数据
        hideLoadingMore: true,  // 默认隐藏加载更多
      };
    }
    return store
  };

  // 顶部下拉刷新
  onRefresh = () => {
    this.setState({
      refreshing: true,
    });
    this.timeId = setTimeout(() => {
      this.setState({
        refreshing: false,
      });
    }, 2000)
  };

  // 路径
  getFetchUrl = (key) => {
    return URL + key + QUERY_STR
  };

  // 底部上拉刷洗
  footerCom = () => {
    return this.store().hideLoadingMore ? null : <View style={styles.footerCom}>
      <ActivityIndicator style={styles.indicator} color={'red'}/>
      <Text>正在加载更多...</Text>
    </View>
  };

  // 页面每个item
  renderItem = ({item}) => {
    return <View style={styles.itemBox}>
      <Text style={styles.itemFullName}>{item.full_name}</Text>
      <Text style={styles.description}>{item.description}</Text>
      <View style={styles.authorStartBox}>
        <View style={styles.authorBox}>
          <Text>Author:</Text>
          <Image source={{uri: item.owner.avatar_url}} style={styles.avatar}/>
        </View>
        <View style={styles.startBox}>
          <Text>Start:</Text>
          <Text>{item.stargazers_count}</Text>
        </View>
        <TouchableOpacity onPress={this.favoriteStar}>
          <Ionicons name={'star-outline'} size={20} color={'#ffda09'}/>
        </TouchableOpacity>
      </View>
    </View>
  };

  // 点击喜欢的星星
  favoriteStar = () => {

  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  itemBox: {
    backgroundColor: '#fff',
    margin: 5,
    padding: 10,
  },
  itemFullName: {
    fontSize: 18,
    marginBottom: 10,
  },
  description: {
    color: '#666',
    marginBottom: 10,
  },
  avatar: {
    width: 20,
    height: 20,
  },
  authorStartBox: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  authorBox: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  startBox: {
    flexDirection: 'row',
  },
  footerCom: {
    justifyContent: 'center',
    alignItems: "center",
  },
  indicator: {
    margin: 10,
  }
});

export default connect(
  state => ({trending: state.trending}),
  {
    onLoadTrendingData: (storeName, url, pageSize) => {
      return createOnLoadTrendingData(storeName, url, pageSize)
    },
    onLoadMoreTrending: (storeName, pageIndex, pageSize, dataArray = [], callBack) => {
      return createOnLoadMoreTrending(storeName, pageIndex, pageSize, dataArray, callBack)
    }
  }
)(TrendingTop);
